package org.spring.springboot.listenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.spring.springboot.dao.biz.UpLoadDao;
import org.spring.springboot.entity.IntervieweeManage;
import org.spring.springboot.server.IntervieweeManageService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EasyExcelListenner extends AnalysisEventListener<IntervieweeManage> {
    @Autowired
    private UpLoadDao upLoadDao;

//    @Autowired
//    private IntervieweeManageService intervieweeManageService;

    private List<IntervieweeManage> datas = new ArrayList<>();
    private static final int BATCH_COUNT = 1000;

    public EasyExcelListenner(UpLoadDao upLoadDao){
        this.upLoadDao = upLoadDao;
    }

    public EasyExcelListenner(){}

    @Override
    public void invoke(IntervieweeManage intervieweeManage, AnalysisContext analysisContext) {
//        //确认数据是否已经存在
//        List<IntervieweeManage> exist = this.exist(upLoadDao, intervieweeManage.getName());
//        //如果数据不存在，执行保存
//        if(exist.size() == 0){
//        //将数据存储在list集合
//            datas.add(intervieweeManage);
//            if(datas.size() >= BATCH_COUNT){
//            saveData();
//            // 存储完成清理 list
//            datas.clear();
//            }
//        }
        datas.add(intervieweeManage);
        //达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(datas.size() >= BATCH_COUNT){
            saveData();
            // 存储完成清理datas
            datas.clear();
        }
    }

    private void saveData() {
        for(IntervieweeManage intervieweeManage : datas){
            this.upLoadDao.insert(intervieweeManage);
        }
    }

    //读取excel表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();//确保所有数据都能入库
        System.out.println("finally");
    }
//    private List<IntervieweeManage> exist(IntervieweeManageService intervieweeManageService, String name){
//        IntervieweeManage intervieweeManage = new IntervieweeManage();
//        intervieweeManage.setName(name);
//        return intervieweeManageService.getUserNameList(intervieweeManage);
//    }
}
